package com.my.vote.pst.user;

import com.my.vote.VoteApplication;
import com.my.vote.entity.EUser;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.RxBusEventManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.io.File;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * 功能描述:
 *
 * @author
 * @date 2018/4/12
 */
public class PstUser extends AbstractPresenter<IPstUser.IVUser> implements IPstUser {

    @Override
    public void updateFile(String file) {
        getView().showLoading(true);
        final BmobFile bmobFile = new BmobFile(new File(file));
        bmobFile.upload(AppCacheManager.getApplication(), new UploadFileListener() {


            @Override
            public void onSuccess() {
                final String url = bmobFile.getFileUrl(AppCacheManager.getApplication());
                final EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
                user.setHeadUrl(url);
                user.update(AppCacheManager.getApplication(), user.getObjectId(), new UpdateListener() {
                    @Override
                    public void onSuccess() {
                        getView().hideLoading();
                        getView().showToast("Update the head image!");
                        AppCacheManager.newInstance().putCache(true,VoteApplication.USER,user);
                        RxBusEventManager.postEvent(user);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        getView().hideLoading();
                        getView().showToast("Update the head image failure!");
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                getView().hideLoading();
                getView().showToast("Update the head image failure!");
            }
        });
    }
}
